package utils;

import java.util.ArrayList;
import java.util.Random;

public class StringUtil {
	/**
	 * 将一个字符串分割为子字符串，然后将结果作为字符串数组返回。
	 * 
	 * @param source
	 *            源字符串
	 * @param separator
	 *            描述用来定义分解位置的字符串。
	 * @return 替换后的字符串
	 */
	public static String[] split(String source, String separator) {
		if (source == null) {
			return null;
		}
		String[] tempArray = new String[1000];
		int lenSep = separator.length(); // the length of separator

		while (source.startsWith(separator)) { // 去掉字符串首部separator
			source = source.substring(lenSep);
		}
		while (source.endsWith(separator)) { // 去掉字符串尾部separator
			source = source.substring(0, source.length() - lenSep);
		}

		int nn = 0;
		while (source.indexOf(separator) != -1) {
			tempArray[nn] = source.substring(0, source.indexOf(separator));
			source = source.substring(source.indexOf(separator) + lenSep);
			nn++;
		}
		if (source.length() >= 1) {
			tempArray[nn] = source;
			nn++;
		}

		String[] tArray = new String[nn];
		for (int i = 0; i < nn; i++) {
			tArray[i] = tempArray[i];
		}
		return tArray;
	}

	/**
	 * 将一个字符串数组中的重复元素去掉，然后将结果作为字符串数组返回。
	 * 
	 * @param source
	 *            源字符串数组
	 * @return 替换后的字符串
	 */
	public static String[] takeOutRepeat(String[] source) {
		ArrayList<String> al = new ArrayList<String>();
		boolean repeat;
		for (int m = 0; m < source.length; m++) {
			repeat = false;
			for (int n = m + 1; n < source.length; n++) {
				if (source[m].equals(source[n])) {
					repeat = true;
					break;
				}
			}
			if (!repeat) {
				al.add(source[m]);
			}
		}
		String[] result = new String[al.size()];
		for (int i = 0; i < result.length; i++) {
			result[i] = (String) al.get(i);
		}
		return result;
	}

	/**
	 * 去掉字符串中的某些子字符串，将 source 中的 takeOutString 全部去掉，并返回新字符串
	 * 
	 * @param source
	 *            源字符串
	 * @param takeOutString
	 *            需要去掉的字符串
	 * 
	 * @return 替换后的字符串
	 */
	public static String takeOut(String source, String takeOutString) {
		int indexPosition;
		indexPosition = source.indexOf(takeOutString);
		if (indexPosition != -1) {
			if ((indexPosition + takeOutString.length()) < source.length()) {
				source = source.substring(0, indexPosition)
						+ source.substring(indexPosition
								+ takeOutString.length());
			} else {
				source = source.substring(0, indexPosition);
			}
		}
		return source;
	}

	/**
	 * 字符串替换，将 source 中的 oldString 全部换成 newString
	 * 
	 * @param source
	 *            源字符串
	 * @param oldString
	 *            老的字符串
	 * @param newString
	 *            新的字符串
	 * @return 替换后的字符串
	 */
	public static String replace(String source, String oldString,
			String newString) {
		StringBuffer output = new StringBuffer();

		int lengthOfSource = source.length(); // 源字符串长度
		int lengthOfOld = oldString.length(); // 老字符串长度

		int posStart = 0; // 开始搜索位置
		int pos; // 搜索到老字符串的位置

		while ((pos = source.indexOf(oldString, posStart)) >= 0) {
			output.append(source.substring(posStart, pos));
			output.append(newString);
			posStart = pos + lengthOfOld;
		}

		if (posStart < lengthOfSource) {
			output.append(source.substring(posStart));
		}

		return output.toString();
	}

	/**
	 * 将字符串格式化成 HTML 代码输出
	 * 
	 * @param str
	 *            要格式化的字符串
	 * @return 格式化后的字符串
	 */
	public static String toHtml(String str) {
		if (str == null || str.length() == 0) {
			return str;
		}
		String html = str;
		html = replace(html, "&", "&amp;");
		html = replace(html, "<", "&lt;");
		html = replace(html, ">", "&gt;");
		html = replace(html, "\r\n", "<br />");
		html = replace(html, "\n", "<br />");
		html = replace(html, " ", "&nbsp;");
		return html;
	}

	/**
	 * 将 HTML 代码转化成文本格式输出
	 * 
	 * @param str
	 *            要格式化的字符串
	 * @return 格式化后的字符串
	 */
	public static String toTxt(String str) {
		if (str == null || str.length() == 0) {
			return str;
		}
		String txt = str;
		txt = replace(txt, "&nbsp;", " ");
		txt = replace(txt, "<br />", "\r\n");
		txt = replace(txt, "&lt;", "<");
		txt = replace(txt, "&gt;", ">");
		txt = replace(txt, "&", "&amp;");
		return txt;
	}

	/**
	 * 把单引号替换为双单引号,用于MSsql
	 */
	public static String toSql(String sqlstr) {
		String strsql = sqlstr;
		strsql = replace(strsql, "'", "''");
		return strsql;
	}

	/**
	 * 从request中转换为中文编码
	 */
	public static String encFromReq(String str) {
		return encodeTo(str, "iso-8859-1", "GBK");
		// return encodeTo(str, "GBK", "gb2312");
	}

	/**
	 * 将从request中取得的字符串数组转换为中文编码
	 * 
	 * @param strs
	 *            从request中取得的字符串数组
	 * @return 转换后的数组
	 */
	public static String[] encFromReq(String[] strs) {
		String[] newStrs = new String[strs.length];
		for (int i = 0; i < strs.length; i++) {
			newStrs[i] = encFromReq(strs[i]);
		}

		return newStrs;
	}

	/**
	 * 从database中转换为中文编码
	 */
	public static String encFromDB(String str) {
		// return encodeTo(str, "iso-8859-1", "GBK");
		return str;
	}

	/**
	 * 编码转换
	 */
	public static String encodeTo(String str, String from, String to) {
		if (str == null || str.length() == 0) {
			return str;
		}
		String temp_p = str;
		try {
			byte[] temp_t = temp_p.getBytes(from);
			String temp = new String(temp_t, to);
			return temp;
		} catch (Exception e) {
			return str;
		}
	}

	/**
	 * 连接String数组
	 * 
	 * @param joinStr
	 *            数组间的连接符
	 * @param strArray
	 *            待连接的数组
	 * @return 连接好的字符串
	 */
	public static String join(String joinStr, String[] strArray) {
		if (strArray == null) {
			return null;
		}
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < strArray.length; i++) {
			if (i == 0) {
				buffer.append(strArray[i]);
			} else {
				buffer.append(joinStr + strArray[i]);
			}
		}
		return buffer.toString();
	}

	/**
	 * 剪切字符串,双字节字符占2个长度
	 * 
	 * @param src
	 *            待剪切的字符串
	 * @param maxLength
	 *            字符串最大长度
	 * @return 剪切后的字符串
	 */
	public static String cutString(String src, int maxLength) {
		return cutString(src, maxLength, maxLength, null);
	}

	/**
	 * 剪切字符串,双字节字符占2个长度
	 * 
	 * @param src
	 *            待剪切的字符串
	 * @param maxLength
	 *            字符串最大长度
	 * @param append
	 *            长度超出后需追加的字符串
	 * @return 剪切后的字符串
	 */
	public static String cutString(String src, int maxLength, String append) {
		return cutString(src, maxLength, maxLength, append);
	}

	/**
	 * 剪切字符串,双字节字符占2个长度
	 * 
	 * @param src
	 *            待剪切的字符串
	 * @param maxLength
	 *            字符串最大长度
	 * @param cutLength
	 *            剪切后的长度
	 * @return 剪切后的字符串
	 */
	public static String cutString(String src, int maxLength, int cutLength) {
		return cutString(src, maxLength, cutLength, null);
	}

	/**
	 * 剪切字符串,双字节字符占2个长度
	 * 
	 * @param src
	 *            待剪切的字符串
	 * @param maxLength
	 *            字符串最大长度
	 * @param cutLength
	 *            剪切后的长度
	 * @param append
	 *            长度超出后需追加的字符串
	 * @return 剪切后的字符串
	 */
	public static String cutString(String src, int maxLength, int cutLength,
			String append) {
		if (src == null) {
			return null;
		}

		byte[] b = src.getBytes();

		// 超过最大长度,需剪切
		if (b.length > maxLength) {
			if (append == null) {
				append = "";
			}
			if (cutLength > maxLength) {
				cutLength = maxLength;
			}
			// 剪切点为双字节字符,需判断剪切点是否是第1个双字节字符
			if (b[cutLength - 1] < 0) {
				boolean isFirst = false;
				for (int i = 0; i < cutLength; i++) {
					if (b[i] < 0) {
						isFirst = !isFirst;
					}
				}
				// 剪切点为第一个双字节字符,去掉
				if (isFirst) {
					cutLength--;
				}
			}
			return cutString(b, cutLength) + append;
		}
		return src;
	}

	/**
	 * 剪切字符串
	 * 
	 * @param src
	 *            待剪切的byte数组
	 * @param cutLength
	 *            剪切后的长度
	 * @return 剪切后的字符串
	 */
	private static String cutString(byte[] src, int cutLength) {
		byte[] b = new byte[cutLength];
		for (int i = 0; i < cutLength; i++) {
			b[i] = src[i];
		}
		return new String(b);
	}

	/**
	 * 返回一个正整数的中文表示，最大99
	 * 
	 * @param num
	 *            int
	 * @return String
	 */
	public static String num2cn(int num) {
		if (num < 0 || num > 99) {
			return "";
		}
		String cn = "";
		String[] cns = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十" };
		int k = 1;
		if (num > 9) {
			k = num / 10;
			num = num % 10;
			if (k > 1) {
				cn += cns[k];
			}
			cn += "十";
			if (num > 0) {
				cn += cns[num];
			}
		} else {
			cn += cns[num];
		}
		return cn;
	}

	/**
	 * 将字符串转化为Short
	 * 
	 * @param value
	 *            String
	 * @return Short
	 */
	public static Short formatShort(String value) {
		Short result = null;
		try {
			result = new Short(value);
		} catch (Exception e) {
		}
		return result;
	}

	/**
	 * 将字符串转化为Byte
	 * 
	 * @param value
	 *            String
	 * @return Byte
	 */
	public static Byte formatByte(String value) {
		Byte result = null;
		try {
			result = new Byte(value);
		} catch (Exception e) {
		}
		return result;
	}

	/**
	 * 将字符串转化为Double
	 * 
	 * @param value
	 *            String
	 * @return Double
	 */
	public static Double formatDouble(String value) {
		Double result = null;
		try {
			result = new Double(value);
		} catch (Exception e) {
		}
		return result;
	}

	/**
	 * 将字符串转化为Float
	 * 
	 * @param value
	 *            String
	 * @return Float
	 */
	public static Float formatFloat(String value) {
		Float result = null;
		try {
			result = new Float(value);
		} catch (Exception e) {
		}
		return result;
	}

	/**
	 * 将字符串转化为Int
	 * 
	 * @param value
	 *            String
	 * @return Integer
	 */
	public static Integer formatInt(String value) {
		Integer result = null;
		try {
			result = new Integer(value);
		} catch (Exception e) {
		}
		return result;
	}

	/**
	 * 将字符串转化为Long
	 * 
	 * @param value
	 *            String
	 * @return Long
	 */
	public static Long formatLong(String value) {
		Long result = null;
		try {
			result = new Long(value);
		} catch (Exception e) {
		}
		return result;
	}

	/**
	 * 获取随机字符串
	 * 
	 * @param length
	 * @return
	 */
	public static String randomStr(int length) {
		String randomStr = "";
		if (length == 0) {
			return randomStr;
		}
		String strSeed = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
		int seedLength = strSeed.length();
		java.util.Random r = new Random(new java.util.Date().getTime());
		for (int i = 0; i < length; i++) {
			int pos = r.nextInt(seedLength);
			randomStr = randomStr + strSeed.substring(pos, pos + 1);
		}
		return randomStr;
	}

	/**
	 * 根据种子获取随机字符串
	 * 
	 * @param strSeed
	 * @param length
	 * @return
	 */
	public static String randomStr(String strSeed, int length) {
		String randomStr = "";
		if (length == 0) {
			return randomStr;
		}
		int seedLength = strSeed.length();
		java.util.Random r = new Random(new java.util.Date().getTime());
		for (int i = 0; i < length; i++) {
			int pos = r.nextInt(seedLength);
			randomStr = randomStr + strSeed.substring(pos, pos + 1);
		}
		return randomStr;
	}
}
